package com.gec.wiki.controller;

import com.gec.wiki.pojo.Ebook;
import com.gec.wiki.pojo.req.EbookQueryReq;
import com.gec.wiki.pojo.req.EbookSaveReq;
import com.gec.wiki.pojo.resp.CommonResp;
import com.gec.wiki.pojo.resp.EbookQueryResp;
import com.gec.wiki.pojo.resp.PageResp;
import com.gec.wiki.service.EbookService;
import com.gec.wiki.utils.CopyUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.validation.Valid;

@RestController
@RequestMapping("/ebook")
public class EbookController {

    @Autowired
    private EbookService ebookService;

    @GetMapping("/getEbookListByPage")
    public CommonResp getEbookListByPage(@Valid EbookQueryReq req){
        PageResp<EbookQueryResp> respPage = ebookService.getEbookListByPage(req);
        CommonResp<PageResp<EbookQueryResp>> resp = new CommonResp<>();
        resp.setContent(respPage);
        return resp;
    }


    @PostMapping("/save")
    public CommonResp save(@Valid @RequestBody EbookSaveReq req){
        Ebook ebook = CopyUtil.copy(req, Ebook.class);
        //会根据是否有id判断   修改（有id）  新增（无id）
        ebookService.saveOrUpdate(ebook);

        CommonResp resp = new CommonResp<>();
        return resp;
    }

    @GetMapping("/remove")
    public CommonResp remove(int id){

        ebookService.removeById(id);

        CommonResp<Object> resp = new CommonResp<>();
        return resp;
    }

    @PostMapping("/uploadImage")
    public CommonResp uploadImage(@RequestParam(value = "file", required = false) MultipartFile file){
        String path = System.getProperty("user.dir");
        System.out.println("path ============== " + path+"\\wiki\\web\\public\\image\\");//"D:\\助教工作\\实训资料\\广东海大\\wiki项目\\wiki\\web\\public\\image\\"
        String imageName = ebookService.uploadImage(file, path+"\\wiki\\web\\public\\image\\");
        CommonResp<Object> resp = new CommonResp<>();
        resp.setContent(imageName);
        return resp;
    }

}
